package edu.ptu.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.ptu.shortlink.admin.common.convention.exception.ClientException;
import edu.ptu.shortlink.admin.dao.entity.UserDO;
import edu.ptu.shortlink.admin.dao.mapper.UserMapper;
import edu.ptu.shortlink.admin.dto.req.UserLoginReqDTO;
import edu.ptu.shortlink.admin.dto.req.UserRegisterReqDTO;
import edu.ptu.shortlink.admin.dto.req.UserUpdateReqDTO;
import edu.ptu.shortlink.admin.dto.resp.UserLoginRespDTO;
import edu.ptu.shortlink.admin.dto.resp.UserRespDTO;
import edu.ptu.shortlink.admin.service.IGroupService;
import edu.ptu.shortlink.admin.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static edu.ptu.shortlink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static edu.ptu.shortlink.admin.common.constant.RedisCacheConstant.USER_LOGIN_KEY;
import static edu.ptu.shortlink.admin.common.enums.UserErrorCodeEnums.*;

/**
 * @BelongsProject: shortlink
 * @BelongsPackage: edu.ptu.shortlink.admin.service.impl
 * @Author: HYJ
 * @CreateTime: 2025-04-22  21:07
 * @Description: 用户接口层实现类
 * @Version: 1.0
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements IUserService {

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;

    private final RedissonClient redissonClient;

    private final StringRedisTemplate redisTemplate;

    private final IGroupService groupService;

    @Override
    public UserRespDTO getUserByUserName(String username) {

        // 创建Lambda查询条件构造器，指定查询UserDO实体类
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                // 添加查询条件：用户名等于参数username
                .eq(UserDO::getUsername, username);


        UserDO userDO = baseMapper.selectOne(queryWrapper);
        UserRespDTO result = new UserRespDTO();

        // 如果查询结果为空，抛出客户端异常 让全局异常拦截器处理
        if (userDO == null) {
            throw new ClientException(USER_NULL);
        }

        BeanUtils.copyProperties(userDO, result);

        return result;
    }

    @Override
    public Boolean availableUsername(String username) {
        // 布隆过滤器用户是否可用->是否存在 true 可用 false 不可用
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }


    @Override
    public void register(UserRegisterReqDTO requestParam) {

        //第一层判断
        if (!availableUsername(requestParam.getUsername())) {
            throw new ClientException(USER_NAME_EXIST);
        }

        // 获取分布式锁 使用用户名作为锁的键->布隆过滤器可能出现误判现象
        RLock lock = redissonClient.getLock(String.format(LOCK_USER_REGISTER_KEY, requestParam.getUsername()));

        // 第二层 判断 尝试加锁
        // 如果获取成功则执行插入操作，否则抛出客户端异常
        try {
            if (lock.tryLock()) {

                try {

                    int inserted = baseMapper.insert(BeanUtil.toBean(requestParam, UserDO.class));
                    //插入失败->抛错
                    if (inserted < 1) {
                        throw new ClientException(USER_SAVE_ERROR);
                    }

                } catch (DuplicateKeyException ex) {
                    //存在重复键->抛错
                    throw new ClientException(USER_EXIST);
                }

                // 布隆过滤器添加用户
                userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());

                //添加一个默认分组
                groupService.saveGroup(requestParam.getUsername(), "默认分组");
                return;
            }
            throw new ClientException(USER_NAME_EXIST);

        } finally {
            // 释放锁
            lock.unlock();
        }
    }

    @Override
    public void update(UserUpdateReqDTO requestParam) {
        //todo 验证当前用户名是否为登录用户 ?? 验证token是否一致
        LambdaUpdateWrapper<UserDO> updateWrapper = Wrappers.lambdaUpdate(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername());
        baseMapper.update(BeanUtil.toBean(requestParam, UserDO.class), updateWrapper);
    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        //1.根据username和password从数据库中查询是否存在user
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getPassword, requestParam.getPassword());

        UserDO userDO = baseMapper.selectOne(queryWrapper);

        //2.对于用户不存在进行处理
        if (userDO == null) {
            throw new ClientException(USER_NULL);
        }

        //3.从redis中检查是否已经存在登录记录
        Map<Object, Object> isLogin = redisTemplate.opsForHash().entries(String.format(USER_LOGIN_KEY, requestParam.getUsername()));
        if (CollUtil.isNotEmpty(isLogin)) {
            String token = isLogin.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> new ClientException("用户登录异常"));
            return new UserLoginRespDTO(token);
        }


        //4.就查询到的user存入redis 并设置过期值 防止一直产生新token

        /**
         * Hash
         * Key: login_用户名
         * Value:
         *  Key: token
         *  Val: JSON 用户消息(字符串)
         */
        String uuid = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForHash().put(String.format(USER_LOGIN_KEY, requestParam.getUsername()), uuid, JSON.toJSONString(userDO));
        redisTemplate.expire(String.format(USER_LOGIN_KEY, requestParam.getUsername()), 30L, TimeUnit.MINUTES);

        //将uuid作为token返回
        return new UserLoginRespDTO(uuid);

    }

    @Override
    public Boolean checkLogin(String username, String token) {
        return redisTemplate.opsForHash().get(String.format(USER_LOGIN_KEY, username), token) != null;
    }

    @Override
    public void logout(String username, String token) {
        if (checkLogin(username, token)) {
            redisTemplate.delete(String.format(USER_LOGIN_KEY, username));
            return;
        }
        throw new ClientException("用户Token不存在或用户未登录");
    }
}
